package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"v8s-watcher/internal/configuration"
	"v8s-watcher/internal/controller"
	"v8s-watcher/internal/db"
	"v8s-watcher/internal/k8s"
	"v8s/logger"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	properties := configuration.ReadProperties()

	logger.BuildLogger(properties.Log)

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute*1)
	mongoClient := db.CreateMongoClient(ctx, properties.Mongo)
	cancel()

	projects := db.CreateProjectsRepository(mongoClient, properties.Mongo)
	k8sClient := k8s.CreateRepository(getKubernetes())

	scheduler := controller.NewScheduler(controller.CreateStatusController(projects, k8sClient), properties.StatusController)

	scheduler.Run()
}

func getKubernetes() *kubernetes.Clientset {
	config, err := rest.InClusterConfig()
	if err != nil {
		dir, err := os.UserHomeDir()
		if err != nil {
			panic(fmt.Sprintf("cannot determine user-home dir: %s", err))
		}

		config, err = clientcmd.BuildConfigFromFlags("", dir+"/kubeconfig.json")
		if err != nil {
			panic(fmt.Sprintf("Unable to get our client configuration: %s", err))
		}
	}

	k8sClient := kubernetes.NewForConfigOrDie(config)
	return k8sClient
}
